//
//  AppDelegate.m
//  17-SandBox沙盒
//
//  Created by mafeng on 16/8/5.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "AppDelegate.h"
#import "Book.h"
@interface AppDelegate ()

@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 沙盒(SandBox)
    // Documents(文件文档, 用户主动数据存储)
    // Libray(资源, 一般用来存放, 程序员要存储的一些数据)
    //     ⬇️
    //   Cache (缓存文件)
    //   Perferences (用户信息和一些用户设置, NSUserDefaults)
    // tmp(临时目录, 下载的临时文件一般放这里)
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLogin"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 2. 获取沙盒路径
    // 下面是两个快捷获取到目录的 C 语言的函数
    // 根目录 家目录
    NSHomeDirectory();
    NSLog(@"Home------%@", NSHomeDirectory());
    // 临时目录 tmp 目录
    NSTemporaryDirectory();
    NSLog(@"Temporary-----%@", NSTemporaryDirectory());
    
    //  C 函数
    //  参数1: 搜索文件夹路径 NSSearchPathDirectory
    //  常用: NSDocumentDirectory NSLibraryDirectory NSCachesDirectory
    //  参数2: 在用户作用域下搜索
    //  参数3: YES or NO YES代表绝对路径(基本上用绝对路径), NO代表相对路径(~)
    NSArray *pathArray =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", pathArray);
    [pathArray firstObject];
    
    // NSBundle  .app文件包
    NSLog(@"%@", [NSBundle mainBundle]);
    
    // 1> 简单的文件读写 Input Output
    NSString *hello = @"Hello, I/O";
    // 一般拼接路径时, 使用 stringByAppendingPathComponent 会自动加斜杠
    NSString *writePath = [[pathArray firstObject] stringByAppendingPathComponent:@"hello.txt"];
    NSError *error = nil;
    [hello writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"存储失败");
    } else {
        NSLog(@"存储成功");
    }
    
    // 2> 读取路径对应的文字
    NSError *readError = nil;
    NSString *readString = [NSString stringWithContentsOfFile:writePath encoding:NSUTF8StringEncoding error:&readError];
    NSLog(@"%@", readString);
    
    // 3> 将 数组 写入本地文件
    NSArray *array = @[@"黄航", @"韩旭", @"爆花", @"宝宝"];
    NSString *arrayPath = [[pathArray firstObject] stringByAppendingPathComponent:@"name.plist"];
    BOOL isArrayWriteSuccess = [array writeToFile:arrayPath atomically:YES];
    if (isArrayWriteSuccess) {
        NSLog(@"写入成功");
    } else {
        NSLog(@"写入失败");
    }
    
    // 4> 将 数组 读取
    NSArray *nameArray = [NSArray arrayWithContentsOfFile:arrayPath];
    NSLog(@"%@", nameArray);
    
    // 5> 将 字典 写入本地
    NSDictionary *dict = @{@"name":@"mafeng",
                           @"age":@"23",
                           @"sex":@"man"};
    NSString *dictPath = [[pathArray firstObject] stringByAppendingPathComponent:@"mafeng.plist"];
    BOOL isDictWriteSuccess = [dict writeToFile:dictPath atomically:YES];
    if (isDictWriteSuccess) {
        NSLog(@"写入成功");
    } else {
        NSLog(@"写入失败");
    }
    
    // 6> 将字典读取出来
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:dictPath];
    NSLog(@"%@", dic);
    
    // 7> 将Data类型写入本地
    UIImage *image = [UIImage imageNamed:@"user"];
    
    NSString *dataPath = [[pathArray firstObject] stringByAppendingPathComponent:@"imageData"];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    
    BOOL isDataWriteSuccess = [imageData writeToFile:dataPath atomically:YES];
    NSLog(@"%@", imageData);
    if (isDataWriteSuccess) {
        NSLog(@"写入成功");
    } else {
        NSLog(@"写入失败");
    }
    
    NSData *imageNewData = [NSData dataWithContentsOfFile:dataPath];
    UIImage *fileImage = [UIImage imageWithData:imageNewData];
    
    // 2. 复杂对象文件读写, 自定义类型
    // 归档/反归档, 序列化/反序列化
    
    // 1> 归档, 将 对象 存储到本地
    Book *book = [Book new];
    book.bookName = @"放弃iOS从我做起";
    book.bookType = @"教育";
    book.bookPrice = @"988.5";
    book.bookAuthor = @"晃晃";
    book.bookAddress = @"演变大学";
    
    NSString *bookPath = [[pathArray firstObject] stringByAppendingPathComponent:@"book.plist"];
    BOOL isSuccess = [NSKeyedArchiver archiveRootObject:book toFile:bookPath];
    if (isSuccess) {
        NSLog(@"写入成功");
    }
    
    // 2> 反归档
    Book *huangBook = [NSKeyedUnarchiver unarchiveObjectWithFile:bookPath];
    NSLog(@"%@", huangBook.bookName);
    
    // 如果对象想要实现归档和反归档
    // 1. 对象对应的类需要签订  Coding
    // 2. 实现写一方法
    //     1> initWithCoder  反归档用
    //     2> encodeWithCoder 归档用
    // 3. 归档时使用 KeyedArchiver
    // 4. 反归档时, 使用 KeyedUnarchiver
    
    // 创建一个文件管理器
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *filePath = [[pathArray firstObject] stringByAppendingPathComponent:@"10101"];
    // 创建文件夹
    [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    // 文件是否存在
    BOOL isExists = [manager fileExistsAtPath:filePath];
    // 删除文件
    BOOL isDele = [manager removeItemAtPath:bookPath error:nil];
    if (isDele) {
        NSLog(@"删除成功");
    } else {
        NSLog(@"删除失败");
    }

    if (isExists) {
        NSLog(@"文件夹存在");
        // 拷贝文件
        NSString *copyPath = [filePath stringByAppendingPathComponent:@"dict.plist"];;
        BOOL isCopy = [manager copyItemAtPath:dictPath toPath:copyPath error:nil];
        if (isCopy) {
            NSLog(@"拷贝成功");
        } else {
            NSLog(@"拷贝失败");
        }
        // 移动文件
        NSString *movePath = [filePath stringByAppendingPathComponent:@"mov.plist"];;
        BOOL isMove = [manager moveItemAtPath:dictPath toPath:movePath error:nil];
        if (isMove) {
            NSLog(@"移动成功");
        } else {
            NSLog(@"移动失败");
        }
        
    } else {
        NSLog(@"文件夹不存在");
    }


    return YES;
} 


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
